import { ref } from "vue";
import {
  LocationQuery,
  RouteComponent,
} from "vue-router";
interface TabViewRecord {
  name: string;
  path: string;
  meta?: any;
  query?: LocationQuery;
  params?: LocationQuery;
  component: RouteComponent;
}

export function useUpdateTabRoutes(tabViews:any) {
  const currentRoute = tabViews.currentRoute.value
  const activeRoute = ref(currentRoute.path)
  const matchComponent = currentRoute.matched[currentRoute.matched.length-1].components.default

  // 添加component
  currentRoute.component = matchComponent
  const view =  {
    path: currentRoute.path,
    name: currentRoute.name,
    meta: currentRoute.meta,
    query: currentRoute.query,
    params: currentRoute.params,
    component: matchComponent
  }
  const tabRoutes = ref<TabViewRecord[]>([])
  tabRoutes.value.push(view)
  localStorage.setItem('tabRoutes', JSON.stringify(tabRoutes.value))

  // 添加tab
  function addTabRoute(currentRoute:any) {
    const matchComponent = currentRoute.matched[currentRoute.matched.length-1].components.default
    const view =  {
      path: currentRoute.path,
      name: currentRoute.name,
      meta: currentRoute.meta,
      query: currentRoute.query,
      params: currentRoute.params,
      component: matchComponent
    }
    tabRoutes.value.push(view)
    localStorage.setItem('tabRoutes', JSON.stringify(tabRoutes.value))
  }

  function changeTabRoute(currentRoute:any) {
    const currentRouteIndex = tabRoutes.value.findIndex(el=>el.path===currentRoute.path)
    console.debug(currentRouteIndex, 'changeTabRoutecurrentRouteIndex')
    if (currentRouteIndex>-1) {
      tabRoutes.value[currentRouteIndex].query = currentRoute.query
      localStorage.setItem('tabRoutes', JSON.stringify(tabRoutes.value))
    }
  }

  // 删除tab
  function deleteTabRoute(currentRoute:any) {
    tabRoutes.value.splice(tabRoutes.value.findIndex(el => el.path===currentRoute.path),1)
    localStorage.setItem('tabRoutes', JSON.stringify(tabRoutes.value))
  }

  return {
    tabRoutes,
    activeRoute,
    addTabRoute,
    deleteTabRoute,
    changeTabRoute
  }
}
